<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Listener;

use App\Websocket\ChatWebsocket;
use App\Websocket\ImWebsocket;
use App\Websocket\ScoreWebsocket;
use Exception;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BeforeMainServerStart;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;

#[Listener]
class BeforeMainServerStartListener implements ListenerInterface
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(protected ContainerInterface $container)
    {
        $this->logger = $container->get(LoggerFactory::class)->get('app', 'default');
    }

    public function listen(): array
    {
        // 指定监听的事件类，可以监听多个事件
        return [
            BeforeMainServerStart::class,
        ];
    }

    /**
     * 事件处理方法，事件触发时调用.
     */
    public function process(object $event): void
    {
        try {
            $redis = $this->container->get(Redis::class);
            $redis->del(ScoreWebsocket::KEY_FDS);
            $redis->del(ChatWebsocket::KEY_FDS);
            $redis->del(ImWebsocket::KEY_FDS);
            $keys = $redis->keys(ChatWebsocket::KEY_FD_INFO . '*');
            if (!empty($keys)) {
                $redis->del($keys);
            }
            $keys = $redis->keys(ChatWebsocket::KEY_GROUP . '*');
            if (!empty($keys)) {
                $redis->del($keys);
            }
            $keys = $redis->keys(ImWebsocket::KEY_USER . '*');
            if (!empty($keys)) {
                $redis->del($keys);
            }
            $this->logger->info('Redis临时数据清除完成');
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface|Exception $e) {
        }
    }
}
